package com.bigshark.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bigshark.api.mapper.UserTokenMapper;
import com.bigshark.api.model.UserToken;
import com.bigshark.api.service.UserTokenService;
import com.bigshark.common.utills.IPUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;

@Service
public class UserTokenServiceImpl extends ServiceImpl<UserTokenMapper,UserToken> implements UserTokenService {

    /**
     * 1小时后过期
     */
    private final static int EXPIRE = 3600 * 1;


    @Override
    public UserToken queryByToken(String token){
        return baseMapper.selectOne(new QueryWrapper<UserToken>().eq("token",token));
    }

    /**
     * 生成登陆token
     * @param userId
     * @param request
     */
    @Override
    public UserToken createToken(Long userId, HttpServletRequest request){
        UserToken userToken = new UserToken();
        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //生成token
        String token = generateToken();

        userToken.setUserId(userId);
        userToken.setExpireTime(expireTime);
        userToken.setToken(token);
        userToken.setIp(IPUtils.getIpAddr(request));
        userToken.setAddTime(now);
        baseMapper.insert(userToken);
        return userToken;
    }

    /**
     * 从新设置过期时间
     * @param token
     */
    @Override
    public void expireToken(String token){
        Date now = new Date();
        UserToken userToken = this.queryByToken(token);
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
        userToken.setExpireTime(expireTime);
        baseMapper.updateById(userToken);
    }

    private String generateToken(){
        return UUID.randomUUID().toString().replace("-", "");
    }

}
